import React, { useEffect, useRef, useState } from "react";
import {
  Card,
  Toast,
  SpinLoading,
  Button,
  Swiper,
  NavBar,
} from "antd-mobile";
import { useSearchParams,useLocation, useNavigate } from "react-router-dom";
import axios from "axios";
import Masonry, { ResponsiveMasonry } from "react-responsive-masonry";
import styles from "./index.module.css"; // 复用 shou 页样式

const FALLBACK_IMG = "https://via.placeholder.com/300x200?text=加载失败";

export default function SearchResult() {
  const [searchParams] = useSearchParams();
  const location = useLocation();
  
  
  const keyword = location.state.keyword || "";
  
  const [list, setList] = useState([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);

  const navigate = useNavigate();
  const loaderRef = useRef(null);
  const observer = useRef(null);

  const fetchData = async (pageNum = 1, reset = false) => {
    if (loading) return;
    setLoading(true);

    try {
      const res = await axios.get("http://127.0.0.1:3000/list", {
        params: {
          page: pageNum,
          pageSize: 10,
          keyword,
        },
      });

      const newData = res.data.info;

      if (reset) {
        setList(newData);
      } else {
        setList((prev) => [...prev, ...newData]);
      }

      setHasMore(newData.length === 10);
    } catch (err) {
      Toast.show({ icon: "fail", content: "加载失败" });
    } finally {
      setTimeout(() => setLoading(false), 200);
    }
  };

  useEffect(() => {
    setPage(1);
    setHasMore(true);
    fetchData(1, true);
  }, [keyword]);

  useEffect(() => {
    if (page === 1) return;
    fetchData(page);
  }, [page]);

  useEffect(() => {
    if (!loaderRef.current) return;
    if (observer.current) observer.current.disconnect();

    observer.current = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && hasMore && !loading) {
        setPage((prev) => prev + 1);
      }
    });

    observer.current.observe(loaderRef.current);
    return () => observer.current?.disconnect();
  }, [hasMore, loading]);

  return (
    <div className={styles.box}>
       <NavBar onBack={() => navigate(-1)} style={{ borderBottom: "1px solid #eee" }}>
        搜索结果
      </NavBar>
      <Card>
        <div style={{ fontWeight: "bold", fontSize: 16 }}>
          搜索结果：<span style={{ color: "#1677ff" }}>{keyword}</span>
        </div>
      </Card>

      <div style={{ padding: 10 }}>
        <ResponsiveMasonry columnsCountBreakPoints={{ 350: 2, 1024: 2 }}>
          <Masonry gutter="10px">
            {list.map((item) => (
              <div
                key={item._id}
                onClick={() => navigate(`/detail/${item._id}`)}
                style={{
                  background: "#fff",
                  borderRadius: 6,
                  overflow: "hidden",
                  transition: "transform 0.2s",
                }}
              >
                <Swiper
                  autoplay
                  loop
                  style={{ width: "100%" }}
                  indicatorProps={{
                    style: {
                      "--dot-color": "#bbb",
                      "--active-dot-color": "#1677ff",
                    },
                  }}
                >
                  {(item.img || []).map((img, index) => (
                    <Swiper.Item key={index}>
                      <img
                        src={img.url}
                        alt=""
                        loading="lazy"
                        onError={(e) => {
                          e.target.onerror = null;
                          e.target.src = FALLBACK_IMG;
                        }}
                        style={{
                          width: "100%",
                          height: "100%",
                          objectFit: "cover",
                          backgroundColor: "#f0f0f0",
                        }}
                      />
                    </Swiper.Item>
                  ))}
                </Swiper>
                <p style={{ padding: "5px 10px" }}>名称：{item.title}</p>
                <p style={{ padding: "5px 10px" }}>
                  价格：{item.price?.toFixed(2) || "未知"}
                </p>
              </div>
            ))}
          </Masonry>
        </ResponsiveMasonry>

        {loading && (
          <div style={{ textAlign: "center", padding: 10 }}>
            <SpinLoading color="primary" />
          </div>
        )}

        {!loading && !hasMore && list.length > 0 && (
          <div style={{ textAlign: "center", color: "#999", padding: 10 }}>
            没有更多内容了
          </div>
        )}

        {list.length === 0 && !loading && (
          <div style={{ textAlign: "center", color: "#999", padding: 30 }}>
            暂无搜索结果
            <Button
              color="primary"
              size="small"
              style={{ marginTop: 10 }}
              onClick={() => {
                setPage(1);
                setHasMore(true);
                fetchData(1, true);
              }}
            >
              点击重试
            </Button>
          </div>
        )}

        <div ref={loaderRef} style={{ height: 1 }} />
      </div>
    </div>
  );
}
